package cn.com.guage.search;

import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

public class BinarySearchTest {

	public static void main(String[] args) {
		int[] array = radomInt();
		Arrays.sort(array);
		System.out.println("数组长度为：" + array.length);
		System.out.println(Arrays.toString(array));
		try (Scanner sc = new Scanner(System.in)) {
			System.out.println("请输入要查找的值:");
			int target = sc.nextInt();
			int index = binarySearch(array, target);
			System.out.println("目标值索引为：" + index);
		}

	}

	public static int[] radomInt() {
		int num = new Random().nextInt(10) + 5;
		int[] array = new int[num];
		for (int i = 0; i < array.length - 1; i++) {
			array[i] = new Random().nextInt(100);
		}
		return array;
	}

	public static int binarySearch(int[] array, int target) {
		int mid = 0;
		int left = 0;
		int right = array.length - 1;
		while (left <= right) {
			mid = (left + right) / 2;
			System.out.println("中间值为：" + array[mid]);
			if (target == array[mid]) {
				return mid;
			} else if (target < array[mid]) {
				right = mid - 1;
			} else if (target > array[mid]) {
				left = mid + 1;
			}
		}
		return -1;

	}
}
